package com.glls.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;

/**
 * 全局过滤器
 *
 * @author junyang
 * @version 1.0.0
 * @date 2025/2/24 9:19
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        if(StrUtil.isEmpty(token)){
            HashMap<Object, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "token不能为空");
            return response(response, result);
        }else{
            if(!"123".equals(token)){
                HashMap<Object, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("msg", "token无效");
                return response(response, result);
            }else{
                return chain.filter(exchange);
            }
        }

    }


    public Mono<Void> response(ServerHttpResponse response, Object data) {
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        String resJson = JSONUtil.toJsonPrettyStr(data);
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(resJson.getBytes());
        return response.writeWith(Flux.just(dataBuffer));//响应json数据

    }




    @Override
    public int getOrder() {
        //通过 返回值 控制该过滤器的执行顺序
        //值越小，优先级越高
        return 0;
    }
}
